import axios from 'axios'
import store from '@/store';

// 创建axios实例
const service = axios.create({
	timeout: 60 * 1000, // ms请求超时时间
	headers: {
		'Content-Type': 'application/json;charset=UTF-8',
		'Language': localStorage.getItem('language') || 'zh-CN',
		'Factoryid': 'XHZQ'
	},
});

const token = localStorage.getItem('token')

// 请求拦截器
service.interceptors.request.use(
	config => {
		// 验证权限
		if (token) {
			config.headers.Authorization = token;
		}
		return config;
	},
	error => {
		// Do something with request error
		Promise.reject(error);
	},
);

// 响应拦截器
service.interceptors.response.use(
	(response) => {
		const res = response.data;
		if (res.code !== 200) {
			return Promise.reject(res);
		}
		return Promise.resolve(res.data)
	},
	// 服务器状态码不是200的情况
	(error) => {
		const {
			status, data
		} = error.response;
		// 错误 500
		if (status === 500) {
			loaderNotification(status, data.message)
		}

		// 错误 404
		if (status === 404) {
			loaderNotification(status, data.message)
		}
		// 错误 401
		if (status === 401) {
			store.dispatch('app/setToken', null)
		}
		return data
		// return Promise.reject(data)
	}
)

export default service;

